import 'package:flutter/material.dart';
import 'dart:async';
import 'package:just_audio/just_audio.dart';
import '../components/language_selector.dart';
import '../constants/app_colors.dart';
import '../services/ms_websocket_trans_service.dart';
import '../utils/ui_helper.dart';
import '../app_logger.dart';
import '../services/recorder_service.dart';
import 'package:share_plus/share_plus.dart';
import '../components/voice_control_widget.dart';
import '../services/translation_settings.dart';

// 消息类型定义
class Message {
  final int id;
  final String sender;
  final String originalText;
  final String translatedText;
  final String originalLanguage;
  final String targetLanguage;
  bool isPlaying;
  String? audioUrl; // 改名为更准确的 audioUrl
  final bool directionSwapped;

  Message({
    required this.id,
    required this.sender,
    required this.originalText,
    required this.translatedText,
    required this.originalLanguage,
    required this.targetLanguage,
    this.isPlaying = false,
    this.audioUrl,
    this.directionSwapped = false,
  });
}

class ConversationScreen extends StatefulWidget {
  const ConversationScreen({Key? key}) : super(key: key);

  @override
  State<ConversationScreen> createState() => _ConversationScreenState();
}

class _ConversationScreenState extends State<ConversationScreen> with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  final List<Message> _messages = [];
  final ScrollController _scrollController = ScrollController();

  // WebSocket服务
  late MSWebSocketTransService _webSocketService;
  final AudioPlayer _audioPlayer = AudioPlayer();
  final RecorderService _recorderService = RecorderService();
  StreamSubscription<PlayerState>? _audioSubscription;

  // 状态变量
  String _sourceLanguage = TranslationSettings.instance.fromLanguage;
  String _targetLanguage = TranslationSettings.instance.toLanguage;
  bool _isRecording = false;
  bool _isWebSocketConnected = false;

  // 当前识别文本
  String _recognizedText = '';

  // 添加一个字段来追踪消息的语言归属
  final Map<String, String> _languageToSender = {};

  // 最新一条消息的ID
  int _lastMessageId = 0;

  @override
  void initState() {
    super.initState();

    _initWebSocket();
    _initRecorderService();
  }

  /// 初始化WebSocket服务
  void _initWebSocket() {
    // 创建WebSocket服务
    log.d('🌐 初始化MSWebSocket翻译服务');
    _webSocketService = MSWebSocketTransService();

    // 设置连接状态回调
    _webSocketService.onConnected = () {
      if (mounted) {
        setState(() {
          _isWebSocketConnected = true;
        });
        log.d('✅ WebSocket连接成功');
      }
    };

    _webSocketService.onDisconnected = () {
      if (mounted) {
        setState(() {
          _isWebSocketConnected = false;
        });
        log.d('🔌 WebSocket连接断开');

        // 如果正在录音，停止录音
        if (_isRecording) {
          log.d('WebSocket断开连接，自动停止录音');
          _stopRecording();
        }
      }
    };

    // 设置ASR识别回调
    _webSocketService.onAsrUpdate = (text, asrSid, isLast) {
      if (mounted) {
        setState(() {
          _recognizedText = text;
        });

        if (isLast) {
          log.d('🎤 收到最终语音识别结果: "$text"');
        }
      }
    };

    // 设置翻译结果回调
    _webSocketService.onTranslation = (translatedText, asrSid, sourceLanguage, targetLanguage) {
      log.d('🔤 收到翻译结果: "$translatedText"');

      // 添加消息到对话列表
      _addMessage(
        _recognizedText.isNotEmpty ? _recognizedText : '语音识别中...',
        translatedText,
        sourceLanguage,
        targetLanguage,
      );
    };

    // 设置TTS音频回调
    _webSocketService.onTtsAudio = (audioUrl, asrSid) {
      log.d('🔊 收到TTS音频: $audioUrl');

      // 更新最后一条消息的音频数据
      if (_messages.isNotEmpty) {
        setState(() {
          _messages.last.audioUrl = audioUrl;
        });
      }
    };

    // 设置错误回调
    _webSocketService.onError = (error) {
      log.d('❌ WebSocket错误: $error');
      if (mounted) {
        UiHelper.showErrorMessage(context, '连接错误: $error');
      }
    };

    // 连接WebSocket
    _connectWebSocket();
  }

  /// 连接WebSocket
  Future<void> _connectWebSocket() async {
    log.d('🔌 开始连接WebSocket服务器...');
    try {
      await _webSocketService.connect();
      log.d('✅ WebSocket连接请求已发送');
    } catch (e) {
      log.d('❌ 连接WebSocket服务器失败: $e');
      if (mounted) {
        UiHelper.showErrorMessage(context, '连接服务器失败: $e');
      }
    }
  }

  /// 初始化录音服务
  void _initRecorderService() {
    _recorderService.initialize(
      callbackId: "conversation_screen",
      onAudioData: (data) {
        // 发送音频数据到WebSocket
        if (_isRecording && _isWebSocketConnected) {
          _webSocketService.sendAudioData(data);
        }
      },
      onError: (errorMsg) {
        if (mounted) {
          UiHelper.showErrorMessage(context, errorMsg);
        }
      },
      onStatusChanged: (status) {
        if (mounted) {
          setState(() {
            _isRecording = status == RecordingStatus.recording;
          });
        }
      },
    );
  }

  /// 添加消息到列表
  void _addMessage(String originalText, String translatedText, String sourceLanguage, String targetLanguage) {

    log.d('🔤 添加消息到列表: $originalText , $translatedText , $sourceLanguage , $targetLanguage');
    setState(() {
      _lastMessageId++;

      // 智能判断发送者
      String sender = _determineSender(sourceLanguage);

      _messages.add(Message(
        id: _lastMessageId,
        sender: sender,
        originalText: originalText,
        translatedText: translatedText,
        originalLanguage: sourceLanguage,
        targetLanguage: targetLanguage,
        isPlaying: false,
      ));
    });

    // 添加消息后自动滚动到底部
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  /// 智能判断消息发送者
  String _determineSender(String sourceLanguage) {
    // 获取语言的基础代码（去掉地区信息）
    String baseLangCode = sourceLanguage.split('-')[0];
    String sourceBaseLangCode = _sourceLanguage.split('-')[0];
    String targetBaseLangCode = _targetLanguage.split('-')[0];

    // 如果这是第一次遇到某种语言，建立映射关系
    if (!_languageToSender.containsKey(baseLangCode)) {
      // 如果匹配源语言，分配给user1
      if (baseLangCode == sourceBaseLangCode) {
        _languageToSender[baseLangCode] = 'user1';
      }
      // 如果匹配目标语言，分配给user2
      else if (baseLangCode == targetBaseLangCode) {
        _languageToSender[baseLangCode] = 'user2';
      }
      // 如果都不匹配，按照出现顺序分配
      else {
        // 检查当前已分配的用户数量
        bool hasUser1 = _languageToSender.containsValue('user1');
        _languageToSender[baseLangCode] = hasUser1 ? 'user2' : 'user1';
      }
    }

    return _languageToSender[baseLangCode] ?? 'user1';
  }

  /// 开始录音
  Future<void> _startRecording() async {
    if (_isRecording) return;

    // 检查WebSocket连接状态
    if (!_isWebSocketConnected) {
      log.d('WebSocket未连接，尝试重新连接');
      await _connectWebSocket();

      // 等待连接完成
      await Future.delayed(const Duration(seconds: 1));
      if (!_isWebSocketConnected) {
        log.d('WebSocket重连失败');
        if (mounted) {
          UiHelper.showErrorMessage(context, 'WebSocket连接失败，请重试');
        }
        return;
      }
    }

    try {
      // 重置识别文本
      setState(() {
        _recognizedText = '';
      });

      // 开始翻译会话 - 使用自动语言检测模式
      await _webSocketService.startAutoDetectTranslation(
        candidateLanguage1: _sourceLanguage,
        candidateLanguage2: _targetLanguage,
        tsEnable: true,
        ttsEnable: true,
        ttsGender: TranslationSettings.instance.useMaleVoice ? 'male' : 'female',
      );

      // 开始录音
      final success = await _recorderService.startRecording(context);
      if (!success) {
        log.d('❌ 开始录音失败');
        if (mounted) {
          UiHelper.showErrorMessage(context, '开始录音失败，请重试');
        }
      } else {
        log.d('✅ 录音已开始');
      }
    } catch (e) {
      log.d('❌ 开始录音翻译失败: $e');
      if (mounted) {
        UiHelper.showErrorMessage(context, '开始录音失败: $e');
      }
    }
  }

  /// 停止录音
  Future<void> _stopRecording() async {
    if (!_isRecording) return;

    try {
      // 停止录音
      await _recorderService.stopRecording();

      // 结束翻译会话
      await _webSocketService.endTranslation();

      log.d('✅ 录音翻译已停止');
    } catch (e) {
      log.d('❌ 停止录音翻译失败: $e');
      if (mounted) {
        UiHelper.showErrorMessage(context, '停止录音时出现问题: $e');
      }
    }
  }

  /// 播放翻译音频
  void _togglePlayTranslation(int messageId) async {
    final message = _messages.firstWhere((msg) => msg.id == messageId, orElse: () => _messages.last);

    // 检查是否有音频数据
    if (message.audioUrl == null || message.audioUrl!.isEmpty) {
      log.d('⚠️ 消息没有音频数据');
      if (mounted) {
        UiHelper.showErrorMessage(context, '没有可播放的音频');
      }
      return;
    }

    try {
      if (message.isPlaying) {
        // 停止播放
        setState(() {
          message.isPlaying = false;
        });
        await _audioPlayer.stop();
        await _audioSubscription?.cancel();
      } else {
        // 停止其他消息的播放状态
        setState(() {
          for (var msg in _messages) {
            msg.isPlaying = false;
          }
          message.isPlaying = true;
        });

        // 停止当前播放
        await _audioPlayer.stop();
        await _audioSubscription?.cancel();

        // 播放新的音频URL
        await _audioPlayer.setUrl(message.audioUrl!);
        await _audioPlayer.play();

        // 监听播放完成
        _audioSubscription = _audioPlayer.playerStateStream.listen((state) {
          if (state.processingState == ProcessingState.completed && mounted) {
            setState(() {
              message.isPlaying = false;
            });
            _audioSubscription?.cancel();
          }
        });
      }
    } catch (e) {
      log.d('❌ 播放翻译音频失败: $e');
      if (mounted) {
        UiHelper.showErrorMessage(context, '播放失败: $e');
        setState(() {
          message.isPlaying = false;
        });
      }
    }
  }

  /// 导出会议纪要
  void _exportMeetingNotes() {
    // 构建会议纪要文本
    String notes = "会议纪要\n\n";
    for (var message in _messages) {
      notes += "${message.sender == 'user1' ? '用户1' : '用户2'}: ${message.originalText}\n";
      notes += "翻译: ${message.translatedText}\n\n";
    }
    Share.share(notes);
  }

  /// 切换语言
  void _swapLanguages() {
    setState(() {
      final temp = _sourceLanguage;
      _sourceLanguage = _targetLanguage;
      _targetLanguage = temp;

      // 清空语言映射，重新建立关系
      _languageToSender.clear();
    });

    // 同步更新到 preferences
    TranslationSettings.instance.fromLanguage = _sourceLanguage;
    TranslationSettings.instance.toLanguage = _targetLanguage;

    // 更新服务的语言设置
    _webSocketService.setLanguages(
      from: _sourceLanguage,
      to: _targetLanguage,
    );

    log.d('🔄 语言已切换: $_sourceLanguage ↔ $_targetLanguage');
  }

  @override
  bool get wantKeepAlive => true;  // 添加此属性以保持页面状态

  @override
  void dispose() {
    // 取消音频订阅
    _audioSubscription?.cancel();

    // 释放滚动控制器
    _scrollController.dispose();

    // 释放音频播放器
    _audioPlayer.dispose();

    // 断开WebSocket连接
    _webSocketService.dispose();

    // 释放录音服务资源
    _recorderService.dispose();

    // 移除录音服务的回调
    _recorderService.removeCallbacks("conversation_screen");

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: LanguageSelector(
          sourceLanguage: _sourceLanguage,
          targetLanguage: _targetLanguage,
          onSwap: _swapLanguages,
          onSourceLanguageChanged: (language) {
            setState(() {
              _sourceLanguage = language;
              // 清空语言映射，重新建立关系
              _languageToSender.clear();
            });
            // 同步更新到 preferences
            TranslationSettings.instance.fromLanguage = language;
            _webSocketService.setLanguages(
              from: _sourceLanguage,
              to: _targetLanguage,
            );
            log.d('🌐 源语言已更改为: $language');
          },
          onTargetLanguageChanged: (language) {
            setState(() {
              _targetLanguage = language;
              // 清空语言映射，重新建立关系
              _languageToSender.clear();
            });
            // 同步更新到 preferences
            TranslationSettings.instance.toLanguage = language;
            _webSocketService.setLanguages(
              from: _sourceLanguage,
              to: _targetLanguage,
            );
            log.d('🌐 目标语言已更改为: $language');
          },
          isCompact: true,
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.summarize),
            onPressed: _exportMeetingNotes,
            tooltip: '导出会议纪要',
          ),
        ],
      ),
      body: Stack(
        children: [
          // 根据消息数量决定显示内容
          _messages.isEmpty ? _buildEmptyState() : _buildMessageList(),

          // 专业的语音控制组件
          VoiceControlWidget(
            state: _getVoiceControlState(),
            recognizedText: _recognizedText,
            onStartRecording: _startRecording,
            onStopRecording: _stopRecording,
            bottomPadding: 20,
          ),
        ],
      ),
    );
  }

  // 获取语音控制状态
  VoiceControlState _getVoiceControlState() {
    if (!_isRecording) {
      return VoiceControlState.idle;
    } else if (_recognizedText.isEmpty) {
      return VoiceControlState.starting;
    } else {
      return VoiceControlState.recording;
    }
  }

  // 构建消息列表
  Widget _buildMessageList() {
    // 更保守的padding计算
    double bottomPadding = 100.0; // 基础padding

    if (_isRecording) {
      if (_recognizedText.isNotEmpty) {
        bottomPadding = 140.0; // 有文本时的padding
      } else {
        bottomPadding = 100.0; // 仅录音时的padding
      }
    }

    return ListView.builder(
      controller: _scrollController,
      padding: EdgeInsets.fromLTRB(8.0, 8.0, 8.0, bottomPadding),
      itemCount: _messages.length,
      itemBuilder: (context, index) {
        final message = _messages[index];
        return _buildMessageBubble(message);
      },
    );
  }

  // 构建消息气泡
  Widget _buildMessageBubble(Message message) {
    final bool isUser1 = message.sender == 'user1';

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        mainAxisAlignment: isUser1 ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!isUser1) _buildAvatar(message),

          const SizedBox(width: 8),

          Flexible(
            child: Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: isUser1
                    ? AppColors.primary.withValues(alpha: 0.2)
                    : Colors.white,
                borderRadius: BorderRadius.circular(18),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withValues(alpha: 0.05),
                    blurRadius: 5,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 原文
                  Text(
                    message.originalText,
                    style: const TextStyle(
                      fontSize: 16,
                      color: Colors.black87,
                    ),
                  ),

                  const Divider(),

                  // 译文和播放按钮
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          message.translatedText,
                          style: const TextStyle(
                            fontSize: 14,
                            color: Colors.black54,
                            fontStyle: FontStyle.italic,
                          ),
                        ),
                      ),

                      // 播放按钮
                      GestureDetector(
                        onTap: () => _togglePlayTranslation(message.id),
                        child: Container(
                          padding: const EdgeInsets.all(4),
                          decoration: BoxDecoration(
                            color: AppColors.primary.withValues(alpha: 0.1),
                            shape: BoxShape.circle,
                          ),
                          child: Icon(
                            message.isPlaying ? Icons.pause : Icons.play_arrow,
                            color: AppColors.primary,
                            size: 20,
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),

          const SizedBox(width: 8),

          if (isUser1) _buildAvatar(message),
        ],
      ),
    );
  }

  // 构建头像
  Widget _buildAvatar(Message message) {
    // 从BCP-47代码中提取语言简码
    final String langCode = message.originalLanguage.split('-')[0].toUpperCase();

    return CircleAvatar(
      radius: 18,
      backgroundColor: message.sender == 'user1' ? AppColors.primary : AppColors.secondary,
      child: Text(
        langCode,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 12,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  // 添加空状态组件
  Widget _buildEmptyState() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 100),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 插图图标
            Container(
              width: 120,
              height: 120,
              decoration: BoxDecoration(
                color: AppColors.primary.withValues(alpha: 0.1),
                shape: BoxShape.circle,
              ),
              child: const Icon(
                Icons.record_voice_over,
                size: 60,
                color: AppColors.primary,
              ),
            ),

            const SizedBox(height: 24),

            // 标题
            Text(
              '开始同声传译',
              style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),

            const SizedBox(height: 16),

            // 描述文字
            Text(
              '点击下方按钮开始录音\n支持实时语音识别和翻译',
              textAlign: TextAlign.center,
              style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                color: Colors.black54,
                height: 1.5,
              ),
            ),

            const SizedBox(height: 32),

            // 功能说明卡片
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withValues(alpha: 0.05),
                    blurRadius: 10,
                    offset: const Offset(0, 4),
                  ),
                ],
              ),
              child: Column(
                children: [
                  _buildFeatureItem(Icons.mic, '实时语音识别'),
                  const SizedBox(height: 12),
                  _buildFeatureItem(Icons.translate, '即时翻译'),
                  const SizedBox(height: 12),
                  _buildFeatureItem(Icons.volume_up, '语音播放'),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 构建功能说明项
  Widget _buildFeatureItem(IconData icon, String text) {
    return Row(
      children: [
        Icon(
          icon,
          size: 20,
          color: AppColors.primary,
        ),
        const SizedBox(width: 12),
        Text(
          text,
          style: const TextStyle(
            fontSize: 14,
            color: Colors.black87,
          ),
        ),
      ],
    );
  }
}